<template>
  <div class="apply-dialog">
    <el-dialog
      title=""
      :visible.sync="dialogVisible"
      :fullscreen="true"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <LimitTech ref="LimitTech" @showTech="openTech" />
      <Tech ref="Tech" @showLimit="openHelp" />
      <div slot="title" class="flex flex-row align-center justify-content-end">
        <div class="btn-list flex flex-row align-center">
          <el-button
            v-if="workOrdeInfo.status != 0"
            type="warning"
            size="mini"
            :disabled="draftDisabled"
            @click="draftAction(processStructureValue.edges[0])"
          >
            暂存
          </el-button>

          <!-- <el-button
            v-if="workOrdeInfo.id > 0 && workOrdeInfo.status == 0"
            type="warning"
            size="mini"
            @click="recallOrder()"
            :disabled="recallDisabled"
          >
            撤回
          </el-button> -->
          <el-button
            v-for="(item, index) in processStructureValue.edges"
            v-show="
              item.source === processStructureValue.nodes[active].id &&
                workOrdeInfo.status != 0
            "
            :key="index"
            type="primary"
            size="mini"
            :disabled="submitDisabled"
            @click="submitAction(item)"
          >
            {{ item.label }}
          </el-button>
          <!-- <el-button type="primary" size="mini" @click="handlePrint(printData)">
            导出PDF
          </el-button> -->

          <div class="pl15 pr15">
            上报人：<span class="primary-color">{{ name }}</span>
          </div>
          <div class="pl15 pr15">
            最新状态：<span class="primary-color">{{ orderState }}</span>
          </div>
          <div class="ml50" @click="handleClose">
            <i class="el-icon-close cursor-p font22 line-height-32" />
          </div>
        </div>
      </div>
      <div class="app-container">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="mb5"
        />
        <div v-if="dialogVisible" id="printFrom" class="text item">
          <template v-for="(tplItem, tplIndex) in processStructureValue.tpls">
            <el-card
              v-show="
                currentNode.hideTpls === undefined ||
                  currentNode.hideTpls === null ||
                  currentNode.hideTpls.indexOf(tplItem.form_structure.id) === -1
              "
              :key="tplIndex"
              class="box-card apply-box mt10 mb20"
            >
              <div slot="header" class="clearfix flex flex-row align-center">
                <div class="line" />
                <span class="font18 ml10 flex-auto">{{
                  tplItem.form_name
                }}</span>
                <el-button
                  v-if="tplIndex == 0"
                  id="no-print"
                  type="danger"
                  round
                  icon="el-icon-thumb"
                  size="small"
                  @click="openHelp"
                >申报指引</el-button>
              </div>
              <fm-generate-form
                :ref="'generateForm-' + tplItem.id"
                :preview="
                  currentNode.hideTpls === undefined ||
                    currentNode.hideTpls === null ||
                    currentNode.hideTpls.indexOf(tplItem.form_structure.id) === -1
                    ? false
                    : true
                "
                :remote="remoteFunc"
                :value="tplItem.form_data"
                :data="tplItem.form_structure"
                :disabled="
                  currentNode.readonlyTpls === undefined ||
                    currentNode.readonlyTpls === null ||
                    currentNode.hideTpls.indexOf(tplItem.form_structure.id) === -1
                    ? null
                    : true
                "
              >
                <el-form-item
                  slot="project_no_block"
                  label="项目编号"
                  prop="projectNo"
                  label-width="130px"
                  class="is-required"
                >
                  <el-input
                    ref="input"
                    v-model="ruleForm.projectNo"
                    type="string"
                    :disabled="currentNode.id != 'userTask1669904963085'"
                    placeholder="管理员填入"
                    style="{ width: 100% }"
                  />
                </el-form-item>
              </fm-generate-form>
            </el-card>
          </template>
        </div>
        <!-- <hr style="background-color: #d9d9d9; border:0; height:1px;" /> -->
        <!-- <div class="text item" style="text-align: center;margin-top:18px">
              <el-button
                v-for="(item, index) in processStructureValue.edges"
                v-show="item.source === processStructureValue.nodes[active].id"
                :key="index"
                type="primary"
                :disabled="submitDisabled"
                @click="submitAction(item)"
              >
                {{ item.label }}
              </el-button>
            </div> -->
      </div>
    </el-dialog>
    <LeaderDialog ref="leaderRef" @selectLeader="selectLeader" />
  </div>
</template>

<script>
import Vue from 'vue'
import { GenerateForm } from '@/components/VueFormMaking'
import 'form-making/dist/FormMaking.css'
Vue.component(GenerateForm.name, GenerateForm)
import LimitTech from './limitTech/index.vue'
import LeaderDialog from './leader/index.vue'
import Tech from './tech/index.vue'
import {
  processStructure,
  createWorkOrder,
  draftWorkOrder,
  updateWorkOrder,
  recallWorkOrder
} from '@/api/xjs/work-order'
import { listAllUser } from '@/api/system/sysuser'
import {getOrdinaryDeptList, newGetUserList, newTreeselect} from '@/api/system/dept'
import { mapGetters } from 'vuex'
import printJS from 'print-js'
export default {
  name: 'ApplyDialog',
  components: {
    LimitTech,
    Tech,
    LeaderDialog
  },
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      structureList:[],
      structureUserList:[],
      models: {

      },
      printData: {
        printable: 'printFrom',
        header: '',
        ignore: ['no-print']
      },
      workOrdeInfo: {
        id: null,
        status: 1
      },
      limitTechList: [],
      selectLimitData: [],
      loading: false,
      dialogVisible: false,
      limitTechVisible: false,
      submitDisabled: false,
      draftDisabled: false,
      recallDisabled: false,
      downloadVisible: false,
      active: 0,
      total: 0,
      processStructureValue: {},
      queryParams: {
        pageIndex: 1,
        pageSize: 5,
        name: undefined
      },
      tpls: [],
      newTpls: [],
      ruleForm: {
        workOrderId: 0,
        title: '',
        projectNo: '',
        process: '',
        classify: '',
        state: [],
        source: '',
        source_state: '',
        process_method: '',
        tpls: {
          form_structure: [],
          form_data: []
        },
        newTpls: {},
        tasks: [],
        status: 0
      },
      rules: {
        title: [{ required: true, message: '请输入工单标题', trigger: 'blur' }]
      },
      processId: null,
      remoteFunc: {
        // 获取用户列表
        async userList(resolve) {
          const res = await listAllUser({})
          const options = res.data
          resolve(options)
        },
        async deptTreeList(resolve) {
          const res = await getOrdinaryDeptList()
          resolve(res.data)
        }
      }
    }
  },
  computed: {
    ...mapGetters(['name']),
    orderState() {
      if (this.workOrdeInfo.id != null) {
        if (this.workOrdeInfo.status == 1) {
          return '未提交(草稿)'
        } else {
          return `${this.workOrdeInfo.current_state_name}【${
            this.workOrdeInfo.principals
          }】`
        }
      } else {
        return '未提交'
      }
    }
  },
  methods: {
    handleChange(v){
      // console.log(1111,v)
      newGetUserList({deptID:v,pageSize:9999,currentPage:1}).then(response => {
        // console.log(2323,response)
        this.structureUserList = response.records;
      })
    },
    getNewDeptTreeList() {
      newTreeselect().then(response => {
        console.log(1122,response.records[0].level)
        this.structureList = response.records[0].level
        // this.deptOptions = response.data
      })
    },
    downLoadDoc(type) {
      var a = document.createElement('a')
      switch (type) {
        case 1:
          a.href =
            '/static/xjs/非限制类使用——甘肃省人民医院医疗技术临床应用审核申请书（操作技术）.docx'
          a.download =
            '非限制类使用——甘肃省人民医院医疗技术临床应用审核申请书（操作技术）.docx'
          break
        case 2:
          a.href =
            '/static/xjs/非限制类使用——甘肃省人民医院医疗技术临床应用审核申请书（检验检查）.docx'
          a.download =
            '非限制类使用——甘肃省人民医院医疗技术临床应用审核申请书（检验检查）.docx'
          break
        case 3:
          a.href = '/static/xjs/限制类备案使用——新技术备案申请表（样表）.docx'
          a.download = '限制类备案使用——新技术备案申请表（样表）.docx'
          break
        case 4:
          a.href = '/static/xjs/限制类备案使用——新技术备案申请表（样表）.docx'
          a.download = '限制类备案使用——新技术备案申请表（样表）.docx'
          break
        case 5:
          a.href = '/static/xjs/限制类备案使用——新技术备案申请表（样表）.docx'
          a.download = '限制类备案使用——新技术备案申请表（样表）.docx'
          break
      }
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    openHelp() {
      this.$refs.Tech.close()
      this.$refs.LimitTech.open()
    },
    openTech() {
      this.$refs.LimitTech.close()
      this.$refs.Tech.open()
    },
    handlePrint(params) {
      printJS({
        maxWidth: 1920,
        documentTitle: '甘肃省人民医院医务一网通办',
        printable: params.printable, // 'printFrom',
        type: params.type || 'html',
        header: params.header, // '表单',
        targetStyles: ['*'],
        ignoreElements: params.ignore || [], // ['no-print']
        properties: params.properties || null
      })
    },
    handleClose(val) {
      this.dialogVisible = false
      this.$refs['ruleForm'].resetFields()
      this.$emit('refreshTable')
    },
    open(processId, workOrderId) {
      this.processId = processId
      this.ruleForm.workOrderId = workOrderId

      this.getProcessNodeList()
    },
    handleLeader() {
      this.$refs.leaderRef.handleInversion()
    },
    getProcessNodeList() {
      processStructure({
        processId: this.processId,
        workOrderId: this.ruleForm.workOrderId
      }).then(response => {
        this.processStructureValue = response.data
        this.newTpls = response.data.tpls
        this.currentNode = this.processStructureValue.nodes[0]
        console.log(this.currentNode)
        this.dialogVisible = true
      })
    },
    draftAction(item) {
      this.draftDisabled = true
      var stateMap = {}
      this.ruleForm.process = this.processId
      this.ruleForm.status = 1
      this.ruleForm.classify = this.processStructureValue.process.classify
      stateMap['id'] = item.target
      this.ruleForm.source_state = this.processStructureValue.nodes[
        this.active
      ].label

      for (var v of this.processStructureValue.nodes) {
        if (v.id === item.target) {
          if (v.assignType !== undefined) {
            stateMap['process_method'] = v.assignType
          }
          if (v.assignValue !== undefined) {
            stateMap['processor'] = Array.from(new Set(v.assignValue))
          }
          stateMap['label'] = v.label
          stateMap['desc'] = v.desc
          break
        }
      }
      this.ruleForm.state = [stateMap]

      this.ruleForm.tpls = {
        form_name: [],
        form_structure: [],
        form_data: []
      }

      var promiseList = []

      this.tpls = []
      for (var tpl of this.newTpls) {
        this.tpls.push({
          tplDataId: tpl.id,
          tplId: tpl.form_structure.id
        })
      }

      for (var tpl of this.processStructureValue.tpls) {
        // tpl.form_structure.id = tpl.id;
        this.ruleForm.tpls.form_structure.push(tpl.form_structure)
        this.ruleForm.tpls.form_name.push(tpl.form_name)
        promiseList.push(
          this.$refs['generateForm-' + tpl.id][0].getDataNoValidate()
        )
      }

      Promise.all(promiseList)
        .then(values => {
          this.ruleForm.source = this.processStructureValue.nodes[
            this.active
          ].id
          console.log(values)
          for (var item of values) {
            if (item.hasOwnProperty('project_name')) {
              this.ruleForm.title = item.project_name
            }
          }
          if (this.tpls.length > 0) {
            for (var tplDataIndex in this.tpls) {
              this.tpls[tplDataIndex].tplValue = values[tplDataIndex]
            }
            this.ruleForm.newTpls = this.tpls
          }

          this.ruleForm.tpls.form_data = values
          this.ruleForm.is_exec_task = item.isExecuteTask
          draftWorkOrder(this.ruleForm)
            .then(response => {
              if (response.code === 200) {
                console.log(response)
                this.$message({
                  type: 'success',
                  message: '暂存成功!'
                })
                this.workOrdeInfo = response.data.workOrder
                this.ruleForm.workOrderId = this.workOrdeInfo.id
                this.newTpls = response.data.tpls
                this.draftDisabled = false
                console.log(this.processStructureValue.tpls)
              }
            })
            .catch(() => {
              this.draftDisabled = false
            })
        })
        .catch(() => {
          this.draftDisabled = false
        })
    },

    selectLeader(userId) {
      this.ruleForm.state[0]['processor'] = [userId]
      updateWorkOrder(this.ruleForm)
        .then(response => {
          if (response.code === 200) {
            this.$message({
              type: 'success',
              message: '提交成功!'
            })
            this.workOrdeInfo = response.data.workOrder
            this.ruleForm.workOrderId = this.workOrdeInfo.id
            this.handleClose()
            // this.$router.push({ path: "/project/applyList" });
            // this.$router.push({ path: "/process/upcoming" });
          }
        })
        .catch(() => {
          this.submitDisabled = false
        })
    },
    recallOrder() {
      this.recallDisabled = true
      const recallParams = {
        work_oroder_id: this.workOrdeInfo.id,
        process_id: this.workOrdeInfo.process
      }
      recallWorkOrder(recallParams)
        .then(response => {
          if (response.code === 200) {
            this.$message({
              type: 'success',
              message: '撤回成功!'
            })
            this.workOrdeInfo = response.data.workOrder
            this.ruleForm.workOrderId = this.workOrdeInfo.id
            this.recallDisabled = false
            this.submitDisabled = false
            this.recallStatus = 1
            // this.$router.push({ path: "/process/upcoming" });
          }
        })
        .catch(() => {
          this.submitDisabled = false
          this.recallDisabled = false
        })
    },
    submitAction(item) {
      console.log(item)
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.submitDisabled = true
          var stateMap = {}
          this.ruleForm.process = this.processId
          this.ruleForm.status = 0
          this.ruleForm.classify = this.processStructureValue.process.classify
          stateMap['id'] = item.target
          this.ruleForm.source_state = this.processStructureValue.nodes[
            this.active
          ].label
          for (var v of this.processStructureValue.nodes) {
            if (v.id === item.target) {
              if (v.assignType !== undefined) {
                stateMap['process_method'] = v.assignType
              }
              if (v.assignValue !== undefined) {
                stateMap['processor'] = Array.from(new Set(v.assignValue))
              }
              stateMap['label'] = v.label
              stateMap['desc'] = v.desc
              break
            }
          }
          this.ruleForm.state = [stateMap]

          this.ruleForm.tpls = {
            form_name: [],
            form_structure: [],
            form_data: []
          }

          var promiseList = []

          this.tpls = []
          for (var tpl of this.newTpls) {
            this.tpls.push({
              tplDataId: tpl.id,
              tplId: tpl.form_structure.id
            })
          }

          for (var tpl of this.processStructureValue.tpls) {
            // tpl.form_structure.id = tpl.id;
            this.ruleForm.tpls.form_structure.push(tpl.form_structure)
            this.ruleForm.tpls.form_name.push(tpl.form_name)
            promiseList.push(this.$refs['generateForm-' + tpl.id][0].getData())
          }
          Promise.all(promiseList)
            .then(values => {
              this.ruleForm.source = this.processStructureValue.nodes[
                this.active
              ].id
              let leadId = 0
              for (var item of values) {
                if (item.hasOwnProperty('project_name')) {
                  this.ruleForm.title = item.project_name
                }
                if (item.hasOwnProperty('leader_name')) {
                  leadId = item.leader_name
                }
              }
              if (this.tpls.length > 0) {
                for (var tplDataIndex in this.tpls) {
                  this.tpls[tplDataIndex].tplValue = values[tplDataIndex]
                }
                this.ruleForm.newTpls = this.tpls
              }
              this.ruleForm.tpls.form_data = values
              this.ruleForm.is_exec_task = item.isExecuteTask

              // this.handleLeader();
              this.selectLeader(leadId)
              this.submitDisabled = false
            })
            .catch(() => {
              this.submitDisabled = false
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
/* 去掉全选按钮 */
::v-deep .el-table .disabledCheck .cell .el-checkbox__inner {
  display: none !important;
}

::v-deep .el-table .disabledCheck .cell::before {
  content: "请选择";
  text-align: center;
  line-height: 37px;
}
.app-container {
  max-width: 1530px;
  margin: 0 auto;
  background: #ebf4fa;
  border-radius: 12px;
  .apply-box {
    border-radius: 15px;
    .line {
      height: 22px;
      width: 5px;
      background: #277fd6;
    }
  }
}
</style>
